//
//  VDDisplayLayout.m
//  PreComposing
//
//  Created by vedon on 14/7/2016.
//  Copyright © 2016 vedon. All rights reserved.
//

#import "VDDisplayLayer.h"

@interface VDDisplayLayer ()
{
    struct VDDisplayFlay
    {
        unsigned displayAyncLayer:1;
        unsigned cancelDisplayAsyncLayer:1;
        unsigned customeDraw:1;
        
    }_delegateFlags;
}
@end


@implementation VDDisplayLayer

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _displaySentinel = [[VDSentinel alloc] init];
        self.opaque = YES;
    }
    return self;
}

- (void)dealloc
{
    [self.displaySentinel increment];
}

- (void)layoutSublayers
{
    [super layoutSublayers];
}

- (void)setNeedsDisplay
{
    [self cancelAsyncDisplay];
    if (!self.displaySuspended)
    {
        [super setNeedsDisplay];
    }
}

- (void)forceDisplayImmediately
{
    [self display:NO];
}

- (void)cancelAsyncDisplay
{
    [self.displaySentinel increment];
    [self.displayDelegate cancelDisplayAsyncLayout:self];
}

#pragma mark - Override

- (void)display
{
    super.contents = super.contents;
    CALayer *tempLayer = [self.hostLayer  layer];
    [tempLayer display];
    
//    if (!self.displaySuspended)
//    {
//        [self display:self.displaysAsynchronously];
//    }
}

+ (id)defaultValueForKey:(NSString *)key
{
    if ([key isEqualToString:@"displaysAsynchronously"]) {
        return @YES;
    } else {
        return [super defaultValueForKey:key];
    }
}

#pragma mark - Private

- (void)display:(BOOL)asynchronously
{
    [self.displayDelegate displayAsyncLayout:self asynchronously:asynchronously];
}

#pragma mark - Getter & Setter

- (void)setDisplaySuspended:(BOOL)displaySuspended
{
    if (_displaySuspended != displaySuspended)
    {
        _displaySuspended = displaySuspended;
        if (!_displaySuspended)
        {
            [self setNeedsDisplay];
        }
        else
        {
            [self cancelAsyncDisplay];
        }
    }
}

@end
